import { Reducer } from 'redux';
import { routerRedux } from 'dva/router';
import { Effect } from 'dva';

import { orderBuy } from '@/services/user';

export interface StateType {
  view?: {};
  edit?: {};
}

export interface LoginModelType {
  namespace: string;
  state: StateType;
  effects: {
    submit: Effect;
    orderView: Effect;
    orderEdit: Effect;
  };
  reducers: {
    orderDetail: Reducer<StateType>;
    edit: Reducer<StateType>;
  };
}

const Model: LoginModelType = {
  namespace: 'buy',

  state: {
    view: {},
    edit: {},
  },

  effects: {
    *submit({ payload }, { call, put }) {
      const response = yield call(orderBuy, payload);
      if (response.status == 200) {
        yield put(routerRedux.push({ pathname: '/Success' }));
        yield put({
          type: 'orderDetail',
          payload: response.data,
        });
      }
    },
    *orderView({ payload }, { put }) {
      yield put({
        type: 'orderDetail',
        payload,
      });
    },
    *orderEdit({ payload }, { put }) {
      yield put({
        type: 'edit',
        payload,
      });
      yield put(
        routerRedux.push({
          pathname: '/buyedit',
        }),
      );
    },
  },

  reducers: {
    orderDetail(state, { payload }) {
      return {
        ...state,
        view: payload,
      };
    },
    edit(state, { payload }) {
      return {
        ...state,
        edit: payload,
      };
    },
  },
};

export default Model;
